package easier.window.popup;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import androidx.core.content.res.ResourcesCompat;
import easier.window.window.R;

/**
 * 简化创建window逻辑
 */
public class PopupWindowShow {

    /**
     * 配置一个popup显示
     *
     * @param popupWindow window
     * @param anchor      锚点
     * @param width       宽度
     * @param height      高度
     * @param xOff        偏移
     * @param yOff        偏移
     * @param gravity     基准
     */
    public static void showAsDropDown( PopupWindow popupWindow, View anchor,
        int width, int height,
        int xOff, int yOff,
        int gravity ) {

        baseConfigPopupWindow( popupWindow );

        if ( height == LayoutParams.WRAP_CONTENT ) {
            configDimenSize( popupWindow, anchor );
            popupWindow.setWidth( width );
        } else {

            popupWindow.setWidth( width );
            popupWindow.setHeight( height );
        }

        /* 靠右时需要向左移动View的宽度 */
        int extraOff = 0;

        if ( gravity == Gravity.END || gravity == (Gravity.END | Gravity.BOTTOM) || gravity == (Gravity.END | Gravity.TOP) ) {

            if ( width > 0 ) {
                extraOff = width;
            } else {
                int measuredWidth = popupWindow.getContentView().getMeasuredWidth();
                if ( measuredWidth <= 0 && width == LayoutParams.WRAP_CONTENT ) {
                    int i = MeasureSpec.makeMeasureSpec( anchor.getWidth(), MeasureSpec.AT_MOST );
                    popupWindow.getContentView()
                        .measure( i, MeasureSpec.makeMeasureSpec( 0, MeasureSpec.UNSPECIFIED ) );
                    extraOff = popupWindow.getContentView().getMeasuredWidth();
                } else {
                    extraOff = measuredWidth;
                }
            }
        }

        popupWindow.showAsDropDown( anchor, xOff - extraOff, yOff, gravity );
    }

    /**
     * @param popupWindow 配置该window,有高度,有背景圆角矩形白色,点击外部消失
     * @param anchor      锚点
     */
    public static void showAsDropDown( PopupWindow popupWindow, View anchor ) {

        baseConfigPopupWindow( popupWindow );

        popupWindow.setWidth( LayoutParams.WRAP_CONTENT );
        popupWindow.setHeight( LayoutParams.WRAP_CONTENT );

        popupWindow.showAsDropDown( anchor );
    }

    /**
     * @param popupWindow 配置该window宽度为锚点宽度,有高度,有背景圆角矩形白色,点击外部消失
     * @param anchor      锚点
     */
    public static void showAsDropDownWithAnchorWidth( PopupWindow popupWindow, View anchor ) {

        showAsDropDownWithAnchorWidth( popupWindow, anchor, null );
    }

    /**
     * @param popupWindow  配置该window宽度为锚点宽度,有高度,有背景圆角矩形白色,点击外部消失
     * @param anchor       锚点
     * @param parentAnchor 锚点:用于兼容处理7.1.1bug,该view位于Activity
     */
    public static void showAsDropDownWithAnchorWidth( PopupWindow popupWindow, View anchor, View parentAnchor ) {

        baseConfigPopupWindow( popupWindow );

        configDimenSize( popupWindow, anchor );

        showAsDropDownCompat( popupWindow, anchor, parentAnchor );
    }

    /**
     * @param popupWindow 配置该window,有高度,有背景圆角矩形白色,点击外部消失
     * @param anchor      锚点
     */
    public static void showAsDropDownDimBehind( PopupWindow popupWindow, View anchor ) {

        View contentView = popupWindow.getContentView();
        if ( contentView != null ) {
            FrameLayout frameLayout = new FrameLayout( anchor.getContext() );
            frameLayout.addView( contentView, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT ) );
            popupWindow.setContentView( frameLayout );

            frameLayout.setOnClickListener( new OnClickListener() {
                @Override
                public void onClick( View v ) {

                    popupWindow.dismiss();
                }
            } );
            contentView.setOnClickListener( new OnClickListener() {
                @Override
                public void onClick( View v ) {
                    /* 仅仅屏蔽掉点击事件 */
                }
            } );
        }

        popupWindow.setWidth( LayoutParams.MATCH_PARENT );
        popupWindow.setHeight( popupWindow.getMaxAvailableHeight( anchor ) );

        /* backGround */
        ColorDrawable background = new ColorDrawable( Color.argb( 0x80, 0, 0, 0 ) );
        popupWindow.setBackgroundDrawable( background );

        popupWindow.setFocusable( false );
        popupWindow.setOutsideTouchable( false );

        popupWindow.showAsDropDown( anchor );
    }

    /**
     * @param popupWindow 配置尺寸:主要配置高度不要超过一个定值
     * @param anchor      锚点
     */
    private static void configDimenSize( PopupWindow popupWindow, View anchor ) {

        /* 计算高度
         * 0.最大高度,宽高中最长边
         * 1.如果横屏显示,可用高度小于最大高度,使用可用高度
         * 2.可用高度大于最大高度,有可能超过最大高度,如果实际不超过最大高度:设置为内容高度,否则最大高度
         *  */
        int maxHeight = getMaxHeight( popupWindow.getContentView().getContext() ) / 3;
        int maxAvailableHeight = popupWindow.getMaxAvailableHeight( anchor );
        if ( maxAvailableHeight > maxHeight ) {

            int i = MeasureSpec.makeMeasureSpec( 0, MeasureSpec.UNSPECIFIED );
            popupWindow.getContentView().measure( i, i );
            int measuredHeight = popupWindow.getContentView().getMeasuredHeight();
            if ( measuredHeight < maxHeight ) {
                popupWindow.setHeight( LayoutParams.WRAP_CONTENT );
            } else {
                popupWindow.setHeight( maxHeight );
            }
        } else {
            popupWindow.setHeight( LayoutParams.WRAP_CONTENT );
        }

        popupWindow.setWidth( anchor.getWidth() );
    }

    /**
     * 7.1.1 popupWindow中再次弹出popupWindow会出错
     *
     * @param popupWindow 新弹窗
     * @param anchor      在popup中需要弹出新的popup,新popup需要的锚点
     * @param parent      在popup中需要弹出新的popup,父级的popup使用的锚点
     */
    public static void showAsDropDownCompat( PopupWindow popupWindow, View anchor, View parent ) {

        /* 兼容处理 */
        if ( parent != null ) {
            int[] location = new int[2];
            anchor.getLocationOnScreen( location );

            int[] location1 = new int[2];
            parent.getLocationOnScreen( location1 );

            popupWindow.showAsDropDown( parent, location[0] - location1[0],
                location[1] - location1[1] + (anchor.getHeight() - parent.getHeight()),
                Gravity.TOP | Gravity.START );
        } else {
            try {
                popupWindow.showAsDropDown( anchor );
            } catch ( Exception e ) {
                Log.e( "test", "showAsDropDownCompat: " + e.getMessage() );
            }
        }
    }


    /**
     * @param popupWindow 有高度,有背景圆角矩形白色,点击外部消失
     */
    private static void baseConfigPopupWindow( PopupWindow popupWindow ) {

        popupWindow.setElevation( 20 );
        popupWindow.setBackgroundDrawable(
            ResourcesCompat.getDrawable( popupWindow.getContentView().getResources(), R.drawable.popup_rect_01, null )
        );
        popupWindow.setFocusable( false );
        popupWindow.setOutsideTouchable( true );
    }

    /**
     * @return 获取屏幕最大高度
     */
    private static int getMaxHeight( Context context ) {

        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return Math.max( displayMetrics.widthPixels, displayMetrics.heightPixels );
    }
}
